<template>
<div class="card art-custom-card" :style="{ height: containerMinHeight  }">
  
  <div class="card-header" style="display: flex;justify-content: space-between;align-items: center;">
      <div>
        <i class="iconfont-sys">&#xe67b;</i>
        <span>{{meta.label}}-配置</span>
      </div>
      <ArtTableHeader v-model:columns="columnChecks" @refresh="handleRefresh">
        <template #left>
          <ElButton @click="showDialogForSqlSettings('add')">配置元数据SQL</ElButton>
          <ElButton @click="showDialog('add')">添加元数据SQL未含字段</ElButton>
          <ElButton @click="batchGenerateFields">批量生成元数据SQL字段</ElButton>
          <ElButton @click="batchRemoveFields">批量移除元数据SQL字段</ElButton>
        </template>
      </ArtTableHeader>
  </div>
  
  <div style="padding-bottom: 10px;height: calc(100% - 20px);">
    <!-- 表格 -->
    <ArtTable
      ref="tableRef"
      row-key="id"
      :loading="loading"
      :data="tableData"
      :currentPage="pagination.currentPage"
      :pageSize="pagination.pageSize"
      :total="pagination.total"
      :marginTop="10"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <template #default>
        <ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
      </template>
    </ArtTable>
  </div>
  
  <!-- 元数据SQL配置弹窗 -->
  <ElDialog
    v-model="dialogVisible"
    :title="sqlDialogTitle"
    width="30%"
    align-center
  >
    <ElForm ref="sqlFormRef" :model="formSqlData" :rules="sqlRules" label-width="135px">
      <ElFormItem label="元数据SQL名称" prop="name">
        <ElInput v-model="formSqlData.name" />
      </ElFormItem>
      <ElFormItem label="元数据SQL数据源" prop="datasourceId">
        <ElSelect v-model="formSqlData.datasourceId" placeholder="请选择数据源">
          <ElOption 
            v-for="ds in dataSources" 
            :key="ds.id" 
            :label="ds.name" 
            :value="ds.id" 
          />
        </ElSelect>
      </ElFormItem>
      
      <ElFormItem label="元数据SQL语句" prop="sql">
        <ElInput v-model="formSqlData.sql" type="textarea" :rows="4"/>
      </ElFormItem>
      
      <ElFormItem label="备注" prop="remark">
        <ElInput v-model="formSqlData.remark" type="textarea"/>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSqlSubmit">提交</ElButton>
      </div>
    </template>
  </ElDialog>
  
  <!-- 元数据字段编辑弹窗 -->
  <ElDialog
    v-model="dialogFieldVisible"
    :title="fieldDialogTitle"
    width="30%"
    align-center
  >
    <ElForm ref="fieldFormRef" :model="formData" :rules="fieldRules" label-width="135px">
      <ElFormItem label="字段名称" prop="name">
        <ElInput v-model="formData.name" />
      </ElFormItem>
      <ElFormItem label="字段标识" prop="code">
        <ElInput v-model="formData.code" />
      </ElFormItem>
      
      <ElFormItem label="读写权限" prop="rw">
        <ElSelect v-model="formData.rw">
          <ElOption label="无限制" value="0" />
          <ElOption label="修改" value="1" />
          <ElOption label="读取" value="2" />
          <ElOption label="写入" value="3" />
        </ElSelect>
      </ElFormItem>
      
      <ElFormItem label="是否显示" prop="isDisplay">
        <ElSelect v-model="formData.isDisplay">
          <ElOption label="隐藏" value="0" />
          <ElOption label="显示" value="1" />
        </ElSelect>
      </ElFormItem>
	  <ElFormItem label="是否排序" prop="sortable">
	    <ElSelect v-model="formData.sortable">
	      <ElOption label="否" value="0" />
	      <ElOption label="是" value="1" />
	    </ElSelect>
	  </ElFormItem>
      
      <ElFormItem label="字段类型" prop="type">
        <ElSelect v-model="formData.type">
          <ElOption label="字符串" value="string" />
          <ElOption label="字节(8位)" value="byte" />
          <ElOption label="短整型(16位)" value="short" />
          <ElOption label="整型(32位)" value="int" />
          <ElOption label="长整型(64位)" value="long" />
          <ElOption label="单精度浮点" value="float" />
          <ElOption label="双精度浮点型" value="double" />
          <ElOption label="布尔" value="boolean" />
		  <ElOption label="日期/时间" value="date" />
        </ElSelect>
      </ElFormItem>
	  
	  <ElFormItem label="日期/时间格式" prop="dateFormat" v-if="formData.type === 'date'">
	    <ElInput v-model="formData.dateFormat" />
	  </ElFormItem>
      
      <ElFormItem label="是否SQL字段" prop="isSqlField">
        <ElSelect v-model="formData.isSqlField">
          <ElOption label="是" value="0" />
          <ElOption label="否" value="1" />
        </ElSelect>
      </ElFormItem>
      
      <ElFormItem label="是否映射值" prop="isMappingValue">
        <ElSelect v-model="formData.isMappingValue">
          <ElOption label="正常" value="0" />
          <ElOption label="映射" value="1" />
        </ElSelect>
      </ElFormItem>
      
      <!-- 条件显示映射相关字段 -->
      <template v-if="formData.isMappingValue === '1'">
        <ElFormItem label="映射值源" prop="mappingValueSrc">
          <ElSelect v-model="formData.mappingValueSrc">
            <ElOption label="字典" value="0" />
            <ElOption label="数据库" value="1" />
          </ElSelect>
        </ElFormItem>
        
        <ElFormItem 
          v-if="formData.mappingValueSrc === '0'" 
          label="字典标识" 
          prop="dict"
        >
          <ElInput v-model="formData.dict" />
        </ElFormItem>

        <template v-if="formData.mappingValueSrc === '1'">
          <ElFormItem label="数据源" prop="datasource">
            <ElInput v-model="formData.datasource" />
          </ElFormItem>
          
          <ElFormItem label="取值SQL语句" prop="sql">
            <ElInput v-model="formData.sql" type="textarea" :rows="2"/>
          </ElFormItem>
        </template>
      </template>

      <ElFormItem label="字段排序" prop="sort" >
        <ElInputNumber
          v-model="formData.sort"
          :min="0"
          controls-position="right"
        />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogFieldVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleFieldSubmit">提交</ElButton>
      </div>
    </template>
  </ElDialog>
</div>
</template>

<script setup lang="ts">
  import { h, ref, reactive, onMounted, nextTick } from 'vue'
  import { ElDialog, FormInstance, ElTag } from 'element-plus'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import type { FormRules } from 'element-plus'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
  import { DataSourceService } from '@/api/sys/dataSourceApi'
  import { SearchChangeParams, SearchFormItem } from '@/types'
  import { useCommon } from '@/composables/useCommon'
  import { useWindowSize } from '@vueuse/core'
  const { containerMinHeight } = useCommon()
  const { width } = useWindowSize()
  defineOptions({ name: 'MetadataManagement' })
  
  const meta=ref<any>();
  const props=defineProps({
  	meta: {
  		type: Object,
  		default: () => {}
  	},
  })
  
  // 弹窗控制
  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const dialogFieldType = ref('add')
  const dialogFieldVisible = ref(false)
  
  // 计算弹窗标题
  const sqlDialogTitle = computed(() => 
    dialogType.value === 'add' ? '添加元数据SQL' : '编辑元数据SQL'
  )
  
  const fieldDialogTitle = computed(() => 
    dialogFieldType.value === 'add' ? '添加字段' : '编辑字段'
  )
  
  const loading = ref(false)
  
  // 分页设置
  const pagination = reactive({
    currentPage: 1,
    pageSize: 20,
    total: 0
  })
  
  // 表格实例引用
  const tableRef = ref()
  
  // 表格数据
  const tableData = ref<any[]>([])
  // 选中的行数据
  const selectedRows = ref<any[]>([])
  // 表单引用
  const sqlFormRef = ref<FormInstance>()
  const fieldFormRef = ref<FormInstance>()
  
  // 数据源列表
  const dataSources = ref<any[]>([])
  
  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    { type: 'selection' }, // 勾选列
  	{ prop: 'name', label: '字段名称' },
  	{ prop: 'code', label: '字段标识' },
	{ prop: 'type', label: '字段类型' },
	{
	  prop: 'sortable',
	  label: '是否排序',
	  sortable: false,
	  formatter: (row:any) => {
		  if(row.rw==0){
			  return "否";
		  }
		  else if(row.rw==1){
			  return "是";
		  }else{
			  return "-";
		  }
	  }
	},
	// {
	//   prop: 'width',
	//   label: '控件宽度',
	//   sortable: false,
	// },
    {
      prop: 'isDisplay',
      label: '是否显示',
      formatter: (row:any) => {
        return h(ElTag, { type: getTagType(row.status) }, () => buildTagText(row.status))
      }
    },
  	{
  	  prop: 'rw',
  	  label: '读写权限',
  	  sortable: false,
  	  formatter: (row:any) => {
  		  if(row.rw==0){
  			  return "无限制";
  		  }
  		  else if(row.rw==1){
  			  return "修改";
  		  }else if(row.rw==2){
  			  return "读取";
  		  }else if(row.rw==3){
  			  return "写入";
  		  }else{
  			  return "-";
  		  }
  	  }
  	},
    {
      prop: 'operation',
      label: '操作',
      width: 150,
      // fixed: 'right', // 固定在右侧
      // disabled: true,
      formatter: (row: any) => {
        return h('div', [
          h(ArtButtonTable, {
            type: 'edit',
            onClick: () => showDialog('edit', row)
          }),
          h(ArtButtonTable, {
            type: 'delete',
            onClick: () => deleteDataSource()
          })
        ])
      }
    }
  ])
  
  // 获取标签类型
  // 1: 在线 2: 离线 3: 异常
  const getTagType = (status: string) => {
    switch (status) {
      case '1':
        return 'success'
      case '0':
        return 'danger'
      default:
        return 'info'
    }
  }
  
  // 构建标签文本
  const buildTagText = (status: string) => {
    let text = ''
    if (status === '1') {
      text = '显示'
    } else if (status === '0') {
      text = '隐藏'
    }else{
      text = '未知'
    }
    return text
  }
  
  // 处理表格行选择变化
  const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection
  }
  
  // 处理表格分页变化
  const handleSizeChange = (newPageSize: number) => {
    pagination.pageSize = newPageSize
    getDataSourceList()
  }
  
  const handleCurrentChange = (newCurrentPage: number) => {
    pagination.currentPage = newCurrentPage
    getDataSourceList()
  }
  
  const handleRefresh = () => {
    getDataSourceList()
  }
  
  // 获取用户列表数据
  const getDataSourceList = async () => {
    loading.value = true
    try {
      const { currentPage, pageSize } = pagination
  
      const { records, current, size, total } = await DataSourceService.getDataSourceList({
        current: currentPage,
        size: pageSize
      })
      tableData.value = records
      // 更新分页信息
      Object.assign(pagination, { currentPage: current, pageSize: size, total })
    } catch (error) {
      console.error('获取数据源列表失败:', error)
    } finally {
      loading.value = false
    }
  }
  
  // 删除数据源
  const deleteDataSource = () => {
    ElMessageBox.confirm('确定要删除该数据源吗？', '删除数据源', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(() => {
      ElMessage.success('删除成功')
    })
  }
  
  // 表单数据
  const formData = reactive({
    id: '',
    name: '',
    code: '',
    rw: '0',
    isDisplay: '1',
	sortable:'0',
    type: 'string',
    isSqlField: '0',
    isMappingValue: '0',
    mappingValueSrc: '0',
    dict: '',
    datasource: '',
    sql: '',
    sort: 0,
	dateFormat:''
  })
  
  const formSqlData = reactive({
    id: '',
    name: '',
    datasourceId: '',
    remark: '',
    sql: '',
  })
  
  // 验证规则
  const sqlRules = reactive<FormRules>({
    name: [
      { required: true, message: '请输入元数据SQL名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    datasourceId: [
      { required: true, message: '请选择数据源', trigger: 'change' }
    ],
    sql: [
      { required: true, message: '请输入SQL语句', trigger: 'blur' }
    ]
  })
  
  const fieldRules = reactive<FormRules>({
    name: [
      { required: true, message: '请输入字段名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    code: [
      { required: true, message: '请输入字段标识', trigger: 'blur' }
    ],
    type: [
      { required: true, message: '请选择字段类型', trigger: 'change' }
    ],
    dict: [
      { 
        required: true, 
        message: '请输入字典标识', 
        trigger: 'blur',
        when: () => formData.isMappingValue === '1' && formData.mappingValueSrc === '0'
      }
    ],
    sql: [
      { 
        required: true, 
        message: '请输入取值SQL', 
        trigger: 'blur',
        when: () => formData.isMappingValue === '1' && formData.mappingValueSrc === '1'
      }
    ],
	dateFormat: [
	  { 
	    required: true, 
	    message: '请输入日期/时间格式', 
	    trigger: 'blur',
	    when: () => formData.type === 'date'
	  }
	],
  })
  
  // 获取数据源列表
  const fetchDataSources = async () => {
    try {
      const res = await DataSourceService.getDataSourceList({
        current: 1,
        size: 100
      })
      dataSources.value = res.records
    } catch (error) {
      console.error('获取数据源失败:', error)
    }
  }
  
  // 显示SQL配置弹窗
  const showDialogForSqlSettings = (type: string, row?: any) => {
    dialogType.value = type
    dialogVisible.value = true
    
    nextTick(() => {
      if (sqlFormRef.value) {
        sqlFormRef.value.resetFields()
      }
      
      if (type === 'edit' && row) {
        Object.assign(formSqlData, {
          id: row.id,
          name: row.name,
          datasourceId: row.datasourceId,
          sql: row.sql,
          remark: row.remark
        })
      } else {
        Object.assign(formSqlData, {
          id: '',
          name: '',
          datasourceId: '',
          sql: '',
          remark: ''
        })
      }
    })
  }
  
  // 显示字段编辑弹窗
  const showDialog = (type: string, row?: any) => {
    dialogFieldType.value = type
    dialogFieldVisible.value = true
    
    nextTick(() => {
      if (fieldFormRef.value) {
        fieldFormRef.value.resetFields()
      }
      
      if (type === 'edit' && row) {
        Object.assign(formData, {
          id: row.id,
          name: row.name,
          code: row.code,
          rw: row.rw,
          isDisplay: row.isDisplay,
		  sortable:row.sortable,
          type: row.type,
          isSqlField: row.isSqlField,
          isMappingValue: row.isMappingValue,
          mappingValueSrc: row.mappingValueSrc,
          dict: row.dict,
          datasource: row.datasource,
          sql: row.sql,
		  dateFormat:row.dateFormat||'',
          sort: row.sort || 0
        })
      } else {
        // 设置添加时的默认值
        Object.assign(formData, {
          id: '',
          name: '',
          code: '',
          rw: '0',
          isDisplay: '1',
          type: 'string',
          isSqlField: '0',
          isMappingValue: '0',
          mappingValueSrc: '0',
		  sortable:'0',
          dict: '',
          datasource: '',
          sql: '',
		  dateFormat:'',
          sort: 0
        })
      }
    })
  }
  
  // SQL配置提交
  const handleSqlSubmit = async () => {
    if (!sqlFormRef.value) return
    
    await sqlFormRef.value.validate((valid) => {
      if (valid) {
        ElMessage.success('操作成功')
        dialogVisible.value = false
        // 这里调用实际API
        // if (dialogType.value === 'add') {
        //   await MetadataService.addMetadataSql(formSqlData)
        // } else {
        //   await MetadataService.updateMetadataSql(formSqlData)
        // }
      }
    })
  }
  
  // 字段编辑提交
  const handleFieldSubmit = async () => {
    if (!fieldFormRef.value) return
    
    await fieldFormRef.value.validate((valid) => {
      if (valid) {
        ElMessage.success('操作成功')
        dialogFieldVisible.value = false
        // 这里调用实际API
        // if (dialogFieldType.value === 'add') {
        //   await MetadataService.addMetadataField(formData)
        // } else {
        //   await MetadataService.updateMetadataField(formData)
        // }
      }
    })
  }
  
  // 批量操作
  const batchGenerateFields = () => {
    ElMessageBox.confirm('确定批量生成字段吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      ElMessage.success('批量生成成功')
    })
  }
  
  const batchRemoveFields = () => {
    ElMessageBox.confirm('确定批量移除字段吗?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(() => {
      ElMessage.success('批量移除成功')
    })
  }
  
  watch(props,() => {
  		meta.value=props.meta
  	},
      { immediate: true, deep: true },
  )
  
  // 初始化
  onMounted(() => {
    fetchDataSources()
	getDataSourceList();
  })
</script>